<template>
  <div class="entry-container">
   

    <!-- 词条内容 -->
    <div v-if="entryData" class="entry-content">
      <button class="back-button" @click="handleBack" style="background-color: #f0f0f0; color: #333; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; border-radius: 50%;">
        <el-icon style="color: #333; font-size: 18px;">
          <ArrowLeft />
        </el-icon>
      </button>
          <!-- 返回按钮 -->  <h1 class="page-title">词条详情</h1><br>
      
    
      <div class="header-right"></div>
      <!-- 作者信息 -->
      <div class="author-info">
        <img :src="entryData.publisher.avatar" alt="作者头像" class="author-avatar" />
        <div class="author-details">
          <span class="author-name">{{ entryData.publisher.username }}</span>
          <span class="publish-time">{{ formatDate(entryData.createdAt) }}</span>
        </div>
      </div>

      <!-- 词条标题和状态 -->
      <div class="entry-header">
        <h2 class="entry-title">{{ entryData.entryName }}</h2>
        <div class="entry-status" :class="`status-${entryData.status}`">
          {{ getStatusText(entryData.status) }}
        </div>
      </div>

      <!-- 词条图片 -->
      <div v-if="entryData.entriesPic" class="entry-image-container">
        <img :src="entryData.entriesPic" alt="词条图片" class="entry-image" />
      </div>

      <!-- 词条描述 -->
      <div class="entry-description">
        {{ entryData.description }}
      </div>

      <!-- 词条来源 -->
      <div class="entry-source">
        <span class="source-label">来源：</span>
        <span class="source-content">{{ entryData.source }}</span>
      </div>

      <!-- 词条分类 -->
      <div class="entry-category">
        <span class="category-label">分类：</span>
        <span class="category-content">
          <span v-if="categoryData">{{ categoryData }}</span>
          <span v-else>加载中...</span>
        </span>
      </div>

           <!-- 互动数据 -->
      <div class="entry-stats">
        <div class="stat-item">
          <VanIcon name="eye-o" class="van-icon" />
          <span>{{ formatNumber(entryData.views) }} 浏览</span>
        </div>
        <div class="stat-item" @click="handleLikeClick">
          <VanIcon :name="isLiked ? 'like' : 'like-o'" :class="{ liked: isLiked, 'van-icon': true }" />
          <span>{{ formatNumber(likes) }} 点赞</span>
        </div>
        <div class="stat-item" @click="handleCollectClick">
          <VanIcon :name="isCollected ? 'star' : 'star-o'" :class="{ collected: isCollected, 'van-icon': true }" />
          <span>{{ formatNumber(collects) }} 收藏</span>
        </div>
      </div>
    </div>
    <!-- 评论区 -->
    <div v-if="entryData" class="comment-section">
      <div class="comment-header">
        <h3>评论</h3>
        <span>{{ comments.length }} 条评论</span>
      </div>

      <!-- 评论输入框 -->
      <div class="comment-input-container">
        <div class="user-avatar-small"></div>
        <div class="comment-input-wrapper">
          <textarea 
            v-model="commentContent" 
            class="comment-input" 
            placeholder="写下你的评论..."
            @keydown.enter.ctrl="submitComment"
          ></textarea>
          <div class="comment-input-footer">
            <span class="hint-text">Ctrl+Enter 发送</span>
            <button 
              class="submit-button" 
              @click="submitComment"
              :disabled="!commentContent.trim() || isSubmitting"
            >
              {{ isSubmitting ? '发送中...' : '发送' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 评论列表 -->
      <div class="comments-list">
        <div v-if="isLoadingComments" class="loading-comments">
          <Loading type="spinner" />
          <p>加载评论中...</p>
        </div>
        <div v-else-if="comments.length === 0" class="no-comments">
          <p>暂无评论，快来抢沙发吧！</p>
        </div>
        <div v-else>
          <!-- 父级评论 -->
          <div v-for="comment in comments" :key="comment.commentId" class="comment-item">
            <img :src="comment.user && comment.user.avatar" alt="用户头像" class="comment-avatar" />
            <div class="comment-content-wrapper">
              <div class="comment-header-info">
                <span class="comment-author">{{ comment.user && comment.user.username }}</span>
                <span class="comment-time">{{ formatDate(comment.createdAt) }}</span>
              </div>
              <div class="comment-text">{{ comment.content }}</div>
              <div class="comment-actions">
                <button class="comment-action-btn" @click="toggleReply(comment.commentId)">
                  <Icon name="chat-o" size="14" />
                  <span>回复</span>
                </button>
              </div>

              <!-- 回复输入框 -->
              <div v-if="replyingTo === comment.commentId" class="reply-input-container" :data-reply-to="comment.commentId">
                <textarea 
                  v-model="replyContent"
                  class="reply-input"
                  :placeholder="`回复 @${comment.user && comment.user.username || ''}...`"
                  @keydown.enter.ctrl="submitReply(comment.commentId)"
                ></textarea>
                <div class="reply-input-footer">
                  <button class="cancel-reply-btn" @click="cancelReply">取消</button>
                  <button 
                    class="submit-reply-btn" 
                    @click="submitReply(comment.commentId)"
                    :disabled="!replyContent.trim() || isSubmittingReply"
                  >
                    {{ isSubmittingReply ? '发送中...' : '发送' }}
                  </button>
                </div>
              </div>

              <!-- 子级评论 -->
              <div v-if="comment.children && comment.children.length > 0" class="replies-list">
                <div v-for="reply in comment.children" :key="reply.commentId" class="reply-item">
                  <img :src="reply.user && reply.user.avatar" alt="用户头像" class="reply-avatar" />
                  <div class="reply-content-wrapper">
                    <div class="reply-header-info">
                      <span class="reply-author">{{ reply.user && reply.user.username }}</span>
                      <span class="reply-to">回复</span>
                      <span class="reply-target">{{ comment.user && comment.user.username }}</span>
                      <span class="reply-time">{{ formatDate(reply.createdAt) }}</span>
                    </div>
                    <div class="reply-text">{{ reply.content }}</div>
                    <div class="reply-actions">
                        <!-- 子评论不支持回复和点赞 -->
                      </div>
                  </div>
                </div>
                <!-- 查看更多回复 -->
                <div v-if="comment.hasMoreReplies" class="view-more-replies">
                  <button @click="loadMoreReplies(comment.commentId)" :disabled="comment.loadingMoreReplies">
                    {{ comment.loadingMoreReplies ? '加载中...' : '展开更多回复' }}
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 加载更多评论 -->
          <div v-if="loadingMoreComments" class="loading-more">
            <Loading type="spinner" />
            <p>加载更多评论...</p>
          </div>
          <div v-else-if="hasMoreComments" class="load-more-btn-container">
            <button class="load-more-btn" @click="loadMoreComments" :disabled="loadingMoreComments">
              展开更多评论
            </button>
          </div>
          <div v-else-if="!hasMoreComments && comments.length > 0" class="no-more-comments">
            <p>没有更多评论了</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <Loading type="spinner" />
      <p>加载中...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Loading } from 'vant';
import axios from '../utils/axios.js';

const route = useRoute();
const router = useRouter();

// 从sessionStorage获取用户信息
let user = JSON.parse(sessionStorage.getItem("user")) || {userId: null, username: '', avatar: ''};
let userId = user.userId;
let userName = user.username;
let userAvatar = user.avatar;

const entryData = ref(null);
const categoryData = ref(null);
//现有的点赞数和收藏数
const likes=ref(0);
const collects=ref(0);

//新点赞的次数和收藏次数（限制一次）
const newLikes=ref(0);
const newCollects=ref(0);
//设定是否已经点赞，已经点赞再点一次就取消点赞
const isLiked=ref(false);
const isCollected=ref(false);
/**
 * 从路由参数中获取并解析词条数据
 */
onMounted(() => {
  console.log(1111111111111111111111111111111111111111111111111111)
  console.log(user)
  // 将依赖entryData.value的操作封装成一个函数
  const processEntryData = () => {
    if (!entryData.value) return;
    
    console.log('处理词条数据:', entryData.value);
    
    // 加载评论列表
    loadComments();
    
    // 确保entryData.value存在后再发送请求
    if (entryData.value.categoryId) {
      axios.post("/api/categories/searchById",{
        id:entryData.value.categoryId
      }).then(res => {
          categoryData.value = res.categoryName;
      }).catch(error => {
        console.error('获取分类名称失败:', error);
      });
    }

    //发送到后端增加词条的views数
    if (entryData.value.entryId) {
      axios.post("/api/entries/addViews",{
        entryId:entryData.value.entryId,
        userId:userId
      }).then(res => {
        console.log('增加views数成功:', res);
      }).catch(error => {
        console.error('增加views数失败:', error);
      });
    }

    //查询该用户是否已经点赞
    if (entryData.value.entryId) {
      axios.post("/api/entryLikes/searchIfLiked",{
        entryId:entryData.value.entryId,
        userId:userId
      }).then(res => {
        console.log('查询点赞状态成功:', res);
        // 检查后端返回的点赞状态，处理不同类型的返回值
        const isAlreadyLiked = res.liked === true || res.liked === "true" || res === true;
        if(isAlreadyLiked){
          newLikes.value=1;
          //设定已经点赞
          isLiked.value=true;
        } else {
          // 确保即使后端返回false，状态也被正确设置
          newLikes.value=0;
          isLiked.value=false;
        }
      }).catch(error => {
        console.error('查询点赞状态失败:', error);
      });
    }
    //查询该用户是否已经收藏
    if (entryData.value.entryId) {
      axios.post("/api/entryCollects/searchIfCollected",{
        entryId:entryData.value.entryId,
        userId:userId
      }).then(res => {
        console.log('查询收藏状态成功:', res);
        // 检查后端返回的收藏状态，处理不同类型的返回值
        const isAlreadyCollected = res.collected === true || res.collected === "true" || res === true;
        if(isAlreadyCollected){
          newCollects.value=1;
          //设定已经收藏
          isCollected.value=true;
        } else {
          // 确保即使后端返回false，状态也被正确设置
          newCollects.value=0;
          isCollected.value=false;
        }
      }).catch(error => {
        console.error('查询收藏状态失败:', error);
      });
    }
    //返回浏览记录给后端
    if (entryData.value.entryId) {
      axios.post("/api/browseHistory/addHistory",{
        entryId:entryData.value.entryId,
        userId:userId
      }).then(res => {
        console.log('返回views数成功:', res);
      }).catch(error => {
        console.error('返回views数失败:', error);
      });
    }
  };

  // 从sessionStorage重新获取用户信息
  user = JSON.parse(sessionStorage.getItem("user")) || {userId: null, username: '', avatar: ''};
  userId = user.userId;
  userName = user.username;
  userAvatar = user.avatar;

  console.log('当前用户:', user);
  console.log('当前用户ID:', userId);
  console.log('当前用户名:', userName);
  console.log('当前用户头像:', userAvatar);
  //先判断路由里面有没有数据如果没有则从后端获取
  // if()
  // 方法1: 从路由query中获取完整的词条数据
  const entryDataStr = route.query.entryData;
  // 方法2: 从路由参数中获取entryId
  const entryId = route.query.entryId || route.params.entryId;
  
  // 判断是使用完整数据还是需要从后端获取
  if (entryDataStr) {
    // 情况1: 有完整的entryData数据
    console.log('从路由query获取的原始词条数据:', entryDataStr);
    try {
      // 解析JSON字符串为对象
      entryData.value = JSON.parse(entryDataStr);
      console.log('从路由参数获取的词条数据:', entryData.value);
      //初始化现有的点赞数和收藏数
      likes.value=entryData.value.likes;
      collects.value=entryData.value.collects;
      
      // 数据加载完成后调用处理函数，包含评论加载
      processEntryData();
    } catch (error) {
      console.error('解析词条数据失败:', error);
      // 如果解析失败，可以选择跳转到首页或显示错误提示
      router.push('/home');
    }
  } else if (entryId) {
    // 情况2: 只有entryId，需要从后端获取完整数据
    console.log('只获取到entryId:', entryId, '将从后端查询数据');
    // 显示加载状态
    entryData.value = null;
    
    axios.post('/api/entries/searchById', { entryId: entryId })
      .then(res => {
        // 根据后端API的实际返回格式调整
        // 后端直接返回了entry对象，而不是包装在entryData字段中
        if (res && typeof res === 'object') {
          entryData.value = res;
          console.log('从后端获取的词条数据:', entryData.value);
          //初始化现有的点赞数和收藏数
          likes.value=entryData.value.likes;
          collects.value=entryData.value.collects;
          
          // 数据加载完成后调用处理函数
          processEntryData();
        } else {
          console.error('后端未返回有效的词条数据');
          router.push('/home');
        }
      })
      .catch(error => {
        console.error('从后端获取词条数据失败:', error);
        router.push('/home');
      });
  } else {
    console.error('未找到词条数据和entryId');
    // 如果既没有词条数据也没有entryId，可以选择跳转到首页或显示错误提示
    router.push('/home');
  }

  

});

//点赞返回给后端
const handleLikeClick = () => {
  if(newLikes.value==0){
    console.log(newLikes.value);
    if (entryData.value && entryData.value.entryId) {
      axios.post("/api/entries/addLikes",{
        entryId:entryData.value.entryId,
        userId:userId
      }).then(res => {
        console.log('增加点赞数成功:', res);
        newLikes.value=1;
        likes.value += 1; // 更新点赞数
        //设定已经点赞
        isLiked.value=true;
      }).catch(error => {
        console.error('增加点赞数失败:', error);
      });
      axios.post("/api/entryLikes/addLikes",{
        entryId:entryData.value.entryId,
        authorId:entryData.value.publisher.userId,
        userId:userId
      }).then(res => {
        console.log('增加entryLikes成功:', res);
      }).catch(error => {
        console.error('增加entryLikes失败:', error);
      });

      axios.post("/api/likeNotifications/addEntryNotification",{
        entryName:entryData.value.entryName,//被点赞的词条名称
        authorId:entryData.value.publisher.userId,//被点赞的词条作者id
        userId:userId,//当前用户（点赞者）id
        username:userName,//当前用户(点赞者)username
      }).then(res => {
        console.log('增加likeNotifications成功:', res);
      }).catch(error => {
        console.error('增加likeNotifications失败:', error);
      });
    }
  }else{
    //取消点赞
    if (entryData.value && entryData.value.entryId) {
      axios.post("/api/entries/cancelLikes",{
        entryId:entryData.value.entryId,
        userId:userId
      }).then(res => {
        console.log('取消点赞数成功:', res);
        newLikes.value=0;
        likes.value -= 1; // 更新点赞数
        //设定已经取消点赞
        isLiked.value=false;
      }).catch(error => {
        console.error('取消点赞数失败:', error);
      });
      axios.post("/api/entryLikes/cancelLikes",{
        entryId:entryData.value.entryId,
        authorId:entryData.value.publisher.userId,
        userId:userId
      }).then(res => {
        console.log('取消entryLikes成功:', res);
      }).catch(error => {
        console.error('取消entryLikes失败:', error);
      });
      axios.post("/api/likeNotifications/deleteEntryNotification",{
        entryName:entryData.value.entryName,//被点赞的词条名称
        authorId:entryData.value.publisher.userId,//被点赞的词条作者id
        userId:userId,//当前用户（点赞者）id
        username:userName,//当前用户(点赞者)username
      }).then(res => {
        console.log('取消likeNotifications成功:', res);
      }).catch(error => {
        console.error('取消likeNotifications失败:', error);
      });
    }
  }
}
//收藏返回给后端
const handleCollectClick = () => {
  if(newCollects.value==0){
    if (entryData.value && entryData.value.entryId) {
      axios.post("/api/entries/addCollects",{
        entryId:entryData.value.entryId,
        userId:userId
      }).then(res => {
        console.log('增加收藏数成功:', res);
        newCollects.value=1;
        collects.value += 1; // 更新收藏数
        //设定已经收藏
        isCollected.value=true;
      }).catch(error => {
        console.error('增加收藏数失败:', error);
      });
      axios.post("/api/entryCollects/addCollects",{
        entryId:entryData.value.entryId,
        authorId:entryData.value.publisher.userId,
        userId:userId
      }).then(res => {
        console.log('增加entryCollects成功:', res);
      }).catch(error => {
        console.error('增加entryCollects失败:', error);
      });
    }
  }else{
    //取消收藏
    if (entryData.value && entryData.value.entryId) {
      axios.post("/api/entries/cancelCollects",{
        entryId:entryData.value.entryId,
        userId:userId
      }).then(res => {
        console.log('取消收藏数成功:', res);
        newCollects.value=0;
        collects.value -= 1; // 更新收藏数
        //设定已经取消收藏
        isCollected.value=false;
      }).catch(error => {
        console.error('取消收藏数失败:', error);
      });
      axios.post("/api/entryCollects/cancelCollects",{
        entryId:entryData.value.entryId,
        authorId:entryData.value.publisher.userId,
        userId:userId
      }).then(res => {
        console.log('取消entryCollects成功:', res);
      }).catch(error => {
        console.error('取消entryCollects失败:', error);
      });
    }
  }
}



/**
 * 处理返回按钮点击事件
 */
const handleBack = () => {
  // 检查是否有从搜索页面传来的参数
  const searchKeyword = route.query.searchKeyword;
  const searchCategory = route.query.searchCategory;
  
  if (searchKeyword && typeof searchKeyword === 'string') {
    // 如果是从搜索页面来的，直接导航回搜索页面并带上参数
    router.push({
      name: 'search',
      query: {
        keyword: searchKeyword,
        searchCategory: searchCategory
      }
    });
  } else {
    // 否则使用默认的返回行为
    router.back();
  }
};

/**
 * 格式化日期
 * @param timestamp 时间戳
 * @returns 格式化后的日期字符串
 */
const formatDate = (timestamp) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

/**
 * 格式化数字（添加千位分隔符）
 * @param num 数字
 * @returns 格式化后的数字字符串
 */
const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

/**
 * 获取状态文本
 * @param status 状态代码
 * @returns 状态文本
 */
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  };
  return statusMap[status] || status;
};
/**
 * 发送post请求给后端，更新点赞数和收藏数
 */
const updateInteractData = () => {

}

// 评论相关状态
const comments = ref([]);
const commentContent = ref('');
const replyContent = ref('');
const replyingTo = ref(null);
const replyToTargetId = ref(null);
const isLoadingComments = ref(false);
const isSubmitting = ref(false);
const isSubmittingReply = ref(false);
const showAllReplies = ref([]);
const currentPage = ref(1);
const hasMoreComments = ref(true);
const loadingMoreComments = ref(false);
const loadingMoreReplies = ref({});

/**
 * 加载评论列表
 */
const loadComments = () => {
  console.log('%c开始加载初始评论列表...','color: #8e44ad; font-weight: bold');
  if (entryData.value && entryData.value.entryId) {
    isLoadingComments.value = true;
    axios.post("/api/comments/getCommentsByEntryId", {
      entryId: entryData.value.entryId,
      page: 1,
      limit: 5
    }).then(res => {
      console.log(`%c初始评论加载成功，获取到${res && Array.isArray(res) ? res.length : 0}条评论`,'color: #8e44ad');
      // 处理评论数据
      if (res && Array.isArray(res)) {
        comments.value = res.map(comment => ({
          ...comment,
          // 初始化子评论的加载状态
          hasMoreReplies: comment.children && comment.children.length > 0,
          loadingMoreReplies: false,
          currentReplyPage: 1
        }));
        hasMoreComments.value = res.length === 5;
        currentPage.value = 1;
      }
    }).catch(error => {
      console.error('加载评论失败:', error);
    }).finally(() => {
      isLoadingComments.value = false;
    });
  }
};

/**
 * 加载更多父级评论
 */
const loadMoreComments = () => {
  if (!hasMoreComments.value || loadingMoreComments.value || !entryData.value) {
    console.log(`%c不触发加载更多评论 - hasMoreComments: ${hasMoreComments.value}, loadingMoreComments: ${loadingMoreComments.value}, entryData: ${!!entryData.value}`,'color: #e74c3c');
    return;
  }
  
  console.log(`%c开始加载第${currentPage.value + 1}页评论...`,'color: #27ae60; font-weight: bold');
  loadingMoreComments.value = true;
  currentPage.value++;
  
  axios.post("/api/comments/getCommentsByEntryId", {
    entryId: entryData.value.entryId,
    page: currentPage.value,
    limit: 5
  }).then(res => {
    console.log(`%c第${currentPage.value}页评论加载成功，获取到${res && Array.isArray(res) ? res.length : 0}条评论`,'color: #27ae60');
    if (res && Array.isArray(res)) {
        const newComments = res.map(comment => ({
          ...comment,
          hasMoreReplies: comment.children && comment.children.length > 0,
          loadingMoreReplies: false,
          currentReplyPage: 1
        }));
      comments.value = [...comments.value, ...newComments];
      hasMoreComments.value = res.length === 5;
    } else {
      hasMoreComments.value = false;
      console.log('%c没有更多评论了','color: #e74c3c');
    }
    console.log(`%c当前评论总数: ${comments.value.length}条，当前页码: ${currentPage.value}，是否有更多: ${hasMoreComments.value}`,'color: #f39c12');
  }).catch(error => {
    console.error('加载更多评论失败:', error);
    currentPage.value--; // 出错时恢复页码
  }).finally(() => {
    loadingMoreComments.value = false;
    console.log('%c评论加载状态已重置','color: #95a5a6');
  });
};

/**
 * 加载更多子评论
 */
const loadMoreReplies = (commentId) => {
  const comment = comments.value.find(c => c.commentId === commentId);
  if (!comment || comment.loadingMoreReplies) {
    return;
  }
  
  comment.loadingMoreReplies = true;
  const currentPage = (comment.currentReplyPage || 1) + 1;
  
  axios.post("/api/comments/getChildrenByCommentId", {
    commentId: commentId,
    page: currentPage,
    limit: 5
  }).then(res => {
    console.log('加载更多子评论成功:', res);
    if (res && Array.isArray(res)) {
      // 确保children数组存在
      if (!comment.children) {
        comment.children = [];
      }
      
      // 添加新的子评论
      comment.children = [...comment.children, ...res];
      comment.currentReplyPage = currentPage;
      
      // 如果返回的子评论数量小于5，表示没有更多了
      if (res.length < 5) {
        comment.hasMoreReplies = false;
      }
    }
  }).catch(error => {
    console.error('加载更多子评论失败:', error);
  }).finally(() => {
    comment.loadingMoreReplies = false;
  });
};

/**
 * 提交评论
 */
const submitComment = () => {
  if (!commentContent.value.trim() || isSubmitting.value) {
    return;
  }
  
  if (entryData.value && entryData.value.entryId) {
    isSubmitting.value = true;
    axios.post("/api/comments/addComment", {
      content: commentContent.value.trim(),
      target_type: 'entry',
      target_id: entryData.value.entryId,
      author_id: userId,
      parent_comment_id: null
    }).then(res => {
      console.log('提交评论成功:', res);
      
      // 无论后端返回什么，我们都创建一个新评论对象并添加到页面上
      // 直接创建新评论对象，字段名称必须与模板中使用的完全匹配
      const newComment = {
        commentId: res.commentId || `temp_${Date.now()}`, // 即使后端没返回ID，也使用临时ID
        content: commentContent.value.trim(),
        user: {
          userId: res.userId || '',
          username: res.nickname || res.username || '我', // 使用username与模板匹配
          avatar: res.avatar || ''
        },
        createdAt: new Date().toISOString(), // 使用createdAt与模板匹配
        children: [],
        hasMoreReplies: false,
        loadingMoreReplies: false,
        currentReplyPage: 1
      };
      
      // 将新评论添加到评论列表开头，让用户能立即看到
      comments.value.unshift(newComment);
      
      // 强制Vue更新视图
      // 使用展开数组的方式确保响应性
      comments.value = [...comments.value];
      
      // 重置输入框
      commentContent.value = '';
      
      // 不再重新加载整个评论列表
      // loadComments();
    }).catch(error => {
      console.error('提交评论失败:', error);
      // 可以显示错误提示
    }).finally(() => {
      isSubmitting.value = false;
    });
  }
};

/**
 * 提交回复
 */
const submitReply = (parentCommentId) => {
  if (!replyContent.value.trim() || isSubmittingReply.value) {
    return;
  }
  
  if (entryData.value && entryData.value.entryId) {
    isSubmittingReply.value = true;
    axios.post("/api/comments/addComment", {
      content: replyContent.value.trim(),
      target_type: 'entry',
      target_id: entryData.value.entryId,
      author_id: userId,
      parent_comment_id: parentCommentId
    }).then(res => {
      console.log('提交回复成功:', res);
      
      // 无论后端返回什么，我们都创建一个新回复对象并添加到页面上
      // 找到对应的父评论
      const parentComment = comments.value.find(comment => comment.commentId === parentCommentId);
      if (parentComment) {
        // 确保children数组存在
        if (!Array.isArray(parentComment.children)) {
          parentComment.children = [];
        }
        
        // 直接创建新回复对象，字段名称必须与模板中使用的完全匹配
        const newReply = {
          commentId: res.commentId || `temp_${Date.now()}`, // 即使后端没返回ID，也使用临时ID
          content: replyContent.value.trim(),
          user: {
            userId: res.userId || '',
            username: res.nickname || res.username || '我', // 使用username与模板匹配
            avatar: res.avatar || ''
          },
          createdAt: new Date().toISOString() // 使用createdAt与模板匹配
        };
        
        // 将新回复添加到回复列表开头，让用户能立即看到
        parentComment.children.unshift(newReply);
        
        // 如果父评论之前没有显示回复，现在需要显示
        if (parentComment.children.length === 1) {
          // 确保回复列表是展开状态
          if (!showAllReplies.value.includes(parentCommentId)) {
            showAllReplies.value.push(parentCommentId);
          }
        }
        
        // 强制Vue更新视图
        // 使用展开数组的方式确保响应性
        comments.value = [...comments.value];
      }
      
      // 重置回复状态
      replyContent.value = '';
      replyingTo.value = null;
      replyToTargetId.value = null;
      
      // 不再重新加载整个评论列表
      // loadComments();
    }).catch(error => {
      console.error('提交回复失败:', error);
    }).finally(() => {
      isSubmittingReply.value = false;
    });
  }
};

/**
 * 切换回复输入框
 */
const toggleReply = (commentId, targetId = null) => {
  if (replyingTo.value === commentId && replyToTargetId.value === targetId) {
    // 点击相同的回复按钮，关闭输入框
    replyingTo.value = null;
    replyToTargetId.value = null;
    replyContent.value = '';
  } else {
    // 打开回复输入框
    replyingTo.value = commentId;
    replyToTargetId.value = targetId;
    replyContent.value = '';
    // 滚动到回复输入框
    setTimeout(() => {
      const element = document.querySelector(`[data-reply-to="${commentId}"]`);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'center' });
        element.focus();
      }
    }, 100);
  }
};

/**
 * 取消回复
 */
const cancelReply = () => {
  replyingTo.value = null;
  replyToTargetId.value = null;
  replyContent.value = '';
};

/**
 * 切换显示全部回复
 */
const toggleShowAllReplies = (commentId) => {
  const index = showAllReplies.value.indexOf(commentId);
  if (index > -1) {
    showAllReplies.value.splice(index, 1);
  } else {
    showAllReplies.value.push(commentId);
  }
};

/**
 * 组件卸载时清理资源
 */
onUnmounted(() => {
  // 清理工作，目前没有需要清理的事件监听器
});

// 评论不再支持点赞功能，已移除handleCommentLike函数



</script>

<style scoped>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 页面容器 */
.entry-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8f8f8;
}

/* 头部样式 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: white;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-button {
  width: 40px;
  height: 40px;
  border: none;
  background: none;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #333;
  cursor: pointer;
  border-radius: 50%;
}

.back-button:hover {
  background-color: #f0f0f0;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  flex: 1;
  text-align: center;
}

.header-right {
  width: 40px;
}

/* 词条内容区域 */
.entry-content {
  flex: 1;
  background-color: white;
  padding: 16px;
  margin: 12px;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

/* 作者信息 */
.author-info {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.author-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
}

.author-details {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-size: 15px;
  font-weight: 500;
  color: #333;
}

.publish-time {
  font-size: 13px;
  color: #999;
  margin-top: 2px;
}

/* 词条标题和状态 */
.entry-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.entry-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  line-height: 1.3;
  flex: 1;
  margin-right: 12px;
}

.entry-status {
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 13px;
  font-weight: 500;
  white-space: nowrap;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-approved {
  background-color: #d4edda;
  color: #155724;
}

.status-rejected {
  background-color: #f8d7da;
  color: #721c24;
}

/* 词条图片 */
.entry-image-container {
  width: 100%;
  margin-bottom: 16px;
  border-radius: 8px;
  overflow: hidden;
}

.entry-image {
  width: 100%;
  height: auto;
  object-fit: cover;
}

/* 词条描述 */
.entry-description {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 16px;
  white-space: pre-wrap;
}

/* 词条来源和分类 */
.entry-source,
.entry-category {
  display: flex;
  margin-bottom: 12px;
  font-size: 14px;
}

.source-label,
.category-label {
  color: #666;
  margin-right: 8px;
  font-weight: 500;
}

.source-content,
.category-content {
  color: #333;
  flex: 1;
}

/* 互动数据 */
.entry-stats {
  display: flex;
  justify-content: space-around;
  padding-top: 16px;
  border-top: 1px solid #eee;
  margin-top: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  flex-direction: column;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  transition: color 0.2s;
}

.stat-item:active {
  transform: scale(0.95);
}

.stat-item .van-icon {
  font-size: 20px;
  margin-bottom: 4px;
  transition: color 0.2s;
}

/* 点赞状态样式 */
.stat-item .liked {
  color: #ff4d4f;
}

/* 收藏状态样式 */
.stat-item .collected {
  color: #ff9500;
}

/* 加载状态 */
.loading-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: white;
  margin: 12px;
  border-radius: 12px;
}

.loading-container p {
  margin-top: 12px;
  font-size: 14px;
  color: #666;
}

/* 评论区样式 */
.comment-section {
  background-color: white;
  margin: 0 12px 12px;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.comment-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.comment-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.comment-header span {
  font-size: 14px;
  color: #666;
}

/* 评论输入框 */
.comment-input-container {
  display: flex;
  margin-bottom: 24px;
}

.user-avatar-small {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f0f0f0;
  margin-right: 12px;
  flex-shrink: 0;
}

.comment-input-wrapper {
  flex: 1;
}

.comment-input {
  width: 100%;
  min-height: 80px;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.4;
  resize: vertical;
  outline: none;
  transition: border-color 0.2s;
}

.comment-input:focus {
  border-color: #4285f4;
}

.comment-input-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.hint-text {
  font-size: 12px;
  color: #999;
}

.submit-button {
  padding: 6px 16px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.submit-button:hover:not(:disabled) {
  background-color: #3367d6;
}

.submit-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 评论列表 */
.comments-list {
  margin-top: 8px;
}

.loading-comments,
.no-comments,
.loading-more,
.no-more-comments {
  text-align: center;
  padding: 20px 0;
  color: #999;
}

.loading-more {
  font-size: 14px;
}

.no-more-comments {
  font-size: 14px;
  color: #ccc;
}

/* 展开更多评论按钮 */
.load-more-btn-container {
  text-align: center;
  padding: 16px 0;
}

.load-more-btn {
  padding: 8px 24px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  outline: none;
}

.load-more-btn:hover:not(:disabled) {
  background-color: #3367d6;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(66, 133, 244, 0.2);
}

.load-more-btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: none;
}

.load-more-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.comment-item {
  display: flex;
  margin-bottom: 20px;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  flex-shrink: 0;
  object-fit: cover;
}

.comment-content-wrapper {
  flex: 1;
}

.comment-header-info {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.comment-author {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-right: 8px;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  margin-bottom: 8px;
  word-break: break-word;
}

.comment-actions {
  display: flex;
  gap: 16px;
}

.comment-action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 0;
  background: none;
  border: none;
  font-size: 12px;
  color: #666;
  cursor: pointer;
  transition: color 0.2s;
}

.comment-action-btn:hover {
  color: #4285f4;
}

.comment-action-btn .liked {
  color: #ff4d4f;
}

/* 回复输入框 */
.reply-input-container {
  margin-top: 12px;
  padding: 12px;
  background-color: #f8f8f8;
  border-radius: 8px;
}

.reply-input {
  width: 100%;
  min-height: 60px;
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 13px;
  line-height: 1.4;
  resize: vertical;
  outline: none;
  transition: border-color 0.2s;
}

.reply-input:focus {
  border-color: #4285f4;
}

.reply-input-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 8px;
}

.cancel-reply-btn {
  padding: 4px 12px;
  background-color: #f0f0f0;
  color: #666;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.cancel-reply-btn:hover {
  background-color: #e0e0e0;
}

.submit-reply-btn {
  padding: 4px 12px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.submit-reply-btn:hover:not(:disabled) {
  background-color: #3367d6;
}

.submit-reply-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 回复列表 */
.replies-list {
  margin-top: 16px;
  margin-left: 0px;
  padding-left: 8px;
}

.reply-item {
  display: flex;
  margin-bottom: 16px;
}

.reply-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 8px;
  flex-shrink: 0;
  object-fit: cover;
}

.reply-content-wrapper {
  flex: 1;
}

.reply-header-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 4px;
}

.reply-author {
  font-size: 13px;
  font-weight: 500;
  color: #333;
  margin-right: 4px;
}

.reply-to {
  font-size: 12px;
  color: #999;
  margin-right: 4px;
}

.reply-target {
  font-size: 13px;
  color: #4285f4;
  margin-right: 8px;
}

.reply-time {
  font-size: 11px;
  color: #999;
}

.reply-text {
  font-size: 13px;
  line-height: 1.5;
  color: #333;
  margin-bottom: 6px;
  word-break: break-word;
}

.reply-actions {
  display: flex;
  gap: 12px;
}

.reply-action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 2px 0;
  background: none;
  border: none;
  font-size: 11px;
  color: #666;
  cursor: pointer;
  transition: color 0.2s;
}

.reply-action-btn:hover {
  color: #4285f4;
}

.reply-action-btn .liked {
  color: #ff4d4f;
}

/* 查看更多回复 */
.view-more-replies {
  text-align: center;
  margin-top: 8px;
}

.view-more-replies button {
  padding: 4px 8px;
  background: none;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
  cursor: pointer;
  transition: all 0.2s;
}

.view-more-replies button:hover:not(:disabled) {
  background-color: #f0f0f0;
  border-color: #d0d0d0;
}

.view-more-replies button:disabled {
  color: #ccc;
  border-color: #f0f0f0;
  cursor: not-allowed;
}

/* 响应式调整 */
@media screen and (max-width: 375px) {
  .entry-content {
    padding: 12px;
    margin: 8px;
  }
  
  .entry-title {
    font-size: 20px;
  }
  
  .entry-description {
    font-size: 15px;
  }
  
  .comment-section {
    padding: 12px;
    margin: 0 8px 8px;
  }
  
  .replies-list {
    margin-left: 42px;
    padding-left: 8px;
  }
}
</style>